import axios from "./request";
import { message } from "ant-design-vue";

import store from './../store'

/*
根据文件流导出文件
*/
const exportFile = (res) => {
  // 获取当前的请求头的文件名
  const contentDisposition = res.headers["content-disposition"];
  console.log(contentDisposition)
  // 如果没有，则是后台报错导出失败，处理后台抛出的异常
  if (!contentDisposition) {
    let reader = new FileReader();
    reader.onload = (event) => {
      let content = JSON.parse(reader.result); // 错误信息
      message.error(content.msg || "导出失败！");
    };
    reader.readAsText(res.data);
    return;
  }
  // 获取到请求头的文件名，进行处理
  let filename = decodeURI(
    contentDisposition.split("fileName=")[1] ||
      contentDisposition.split("filename=")[1]
  );
  filename =
    filename.indexOf('"') === -1
      ? filename
      : filename.substring(1, filename.length - 1);
  const blob = new Blob([res.data]);
  const url = window.URL.createObjectURL(blob);
  if (window.navigator.msSaveBlob) {
    try {
      window.navigator.msSaveBlob(blob, filename);
    } catch (e) {
      console.log(e);
    }
  } else {
    let link = document.createElement("a");
    link.style.display = "none";
    link.href = url;
    link.setAttribute("download", filename);
    document.body.appendChild(link);
    link.click();
  }
};
/*
权限判断
*/
const roleFilter = (roleName) => {
  // false 不显示 true 显示
  if(!roleName || store.getters.getUserRoleList.length===0){
    return false;
  }
  return store.getters.getUserRoleList.indexOf(roleName)!==-1;
};

const api = {
  // 获取验证码
  async codeImg(url) {
    return await axios
      .get(url, {
        responseType: "arraybuffer",
      })
      .then((res) => {
        return (
          "data:image/png;base64," +
          window.btoa(
            new Uint8Array(res.data).reduce(
              (data, byte) => data + String.fromCharCode(byte),
              ""
            )
          )
        );
      });
  },
  async download(url, method, data) {
    return await axios
      .request({
        method,
        url,
        data,
        responseType: "blob",
      })
      .then((res) => {
        exportFile(res);
      });
  },
};

export { exportFile, roleFilter, api };
